﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace SBLib.Common.XmlKS
{
    public static class XmlFunc
    {
        public static string SerializeObjectToXml<T>(List<T> ParamObject)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<T>));

                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                {
                    serializer.Serialize(sw, ParamObject);
                    return sb.ToString();
                }
            }
            catch (Exception)
            {
                return "";

            }

        }

        public static string TransformDatabaseDataToXml(string ConnectionString, string SQLStatement, string RootName, string EachRowName)
        {

            try
            {
                using (SqlConnection conn = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(SQLStatement, conn))
                    {

                        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet(RootName);
                            dataAdapter.Fill(ds, EachRowName);

                            StringBuilder sb = new StringBuilder();
                            using (StringWriter sw = new StringWriter(sb))
                            {
                                ds.Tables[0].WriteXml(sw);
                                return sw.ToString();
                            }
                        }

                    }
                }

            }
            catch (Exception ex)
            {

                return ex.Message;
            }
        }


        public static XmlDocument ConvertStringToXML(string xmlstring)
        {
            try
            {
                //convert to xml
                XmlDocument xm = new XmlDocument();
                xm.LoadXml(xmlstring);
                return xm;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
